import { createRouter, createWebHistory } from 'vue-router';
import { appValues, getRouteGuards, getRoutes } from '~/utils/defines';
import { setAppRouter } from './helpers';

export default defineStartup(async (app) => {
  const routes = await getRoutes();
  const router = appValues.router = createRouter({
    history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
    routes,
    scrollBehavior(to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition;
      }
      else {
        return { top: 0, left: 0 };
      }
    },
  });

  /* 获取并设置路由守卫 */
  const routeGuards = await getRouteGuards();
  routeGuards.forEach(guard => guard.setup(router));

  // router.beforeEach((to, from, next) => {
  //   if ((to.query?.share_type === 'InviteSpinDetail' || to.name === 'invitation')) {
  //     next(`/${to?.query?.ic ? `?ic=${to.query?.ic}` : null}`);
  //   }
  //   next();
  // });

  appValues.routeKey = ref(0);
  appValues.refreshRoute = () => {
    appValues.routeKey!.value++;
  };

  setAppRouter(router);
  app.use(router);
});
